// 诅咒系统 - 风险与奖励的平衡机制
(function() {
    'use strict';
    
    class CurseSystem {
        constructor() {
            this.activeCurses = [];
            this.cursePool = [];
            this.blessingPool = [];
            this.curseChance = 0.15; // 15%概率出现诅咒选择
            this.lastCurseOffer = 0;
            this.curseOfferCooldown = 45000; // 45秒冷却
            this.maxCurses = 3; // 最多同时3个诅咒
            
            this.initializeCursePool();
            this.initializeBlessingPool();
        }
        
        initialize() {
            console.log('😈 诅咒系统已激活 - 以痛苦换取力量');
            this.startCurseEvents();
        }
        
        initializeCursePool() {
            this.cursePool = [
                {
                    id: 'fragile_bones',
                    name: '脆弱之骨',
                    description: '受到伤害增加50%',
                    effect: () => {
                        this.addCurseEffect('damage_taken_multiplier', 1.5);
                    },
                    remove: () => {
                        this.removeCurseEffect('damage_taken_multiplier');
                    },
                    blessing: {
                        name: '钢铁之躯',
                        description: '生命值增加100%，伤害增加30%'
                    }
                },
                {
                    id: 'cursed_reload',
                    name: '诅咒弹夹',
                    description: '装弹时间增加200%',
                    effect: () => {
                        this.addCurseEffect('reload_speed_multiplier', 3);
                    },
                    remove: () => {
                        this.removeCurseEffect('reload_speed_multiplier');
                    },
                    blessing: {
                        name: '闪电装弹',
                        description: '瞬间装弹，射速增加50%'
                    }
                },
                {
                    id: 'heavy_feet',
                    name: '沉重步伐',
                    description: '移动速度降低40%',
                    effect: () => {
                        this.addCurseEffect('speed_multiplier', 0.6);
                        if (window.player) window.player.speed *= 0.6;
                    },
                    remove: () => {
                        this.removeCurseEffect('speed_multiplier');
                        if (window.player) window.player.speed /= 0.6;
                    },
                    blessing: {
                        name: '风之步伐',
                        description: '移动速度增加80%，闪避冷却减少50%'
                    }
                },
                {
                    id: 'ammunition_curse',
                    name: '弹药诅咒',
                    description: '弹药消耗增加100%',
                    effect: () => {
                        this.addCurseEffect('ammo_consumption', 2);
                    },
                    remove: () => {
                        this.removeCurseEffect('ammo_consumption');
                    },
                    blessing: {
                        name: '无尽弹药',
                        description: '弹药无限，武器伤害增加40%'
                    }
                },
                {
                    id: 'zombie_attraction',
                    name: '僵尸磁铁',
                    description: '僵尸生成速度增加150%',
                    effect: () => {
                        this.addCurseEffect('zombie_spawn_rate', 2.5);
                    },
                    remove: () => {
                        this.removeCurseEffect('zombie_spawn_rate');
                    },
                    blessing: {
                        name: '屠杀专家',
                        description: '击杀僵尸恢复生命值，连击奖励翻倍'
                    }
                }
            ];
        }
        
        initializeBlessingPool() {
            this.blessingPool = [
                {
                    id: 'divine_protection',
                    name: '神圣护佑',
                    description: '受到致命伤害时有50%概率保留1点生命值',
                    effect: () => {
                        this.addBlessingEffect('death_save', 0.5);
                    }
                },
                {
                    id: 'berserker_rage',
                    name: '狂战士之怒',
                    description: '生命值越低，伤害越高（最高300%）',
                    effect: () => {
                        this.addBlessingEffect('berserker_mode', true);
                    }
                },
                {
                    id: 'lucky_shot',
                    name: '幸运射击',
                    description: '20%概率造成暴击伤害（5倍）',
                    effect: () => {
                        this.addBlessingEffect('critical_chance', 0.2);
                        this.addBlessingEffect('critical_multiplier', 5);
                    }
                }
            ];
        }
        
        startCurseEvents() {
            setInterval(() => {
                this.checkForCurseOffer();
            }, 10000); // 每10秒检查一次
        }
        
        checkForCurseOffer() {
            const now = Date.now();
            
            // 检查冷却时间和概率
            if (now - this.lastCurseOffer < this.curseOfferCooldown) return;
            if (this.activeCurses.length >= this.maxCurses) return;
            if (window.gameEngine?.gameState !== 'playing') return;
            if (Math.random() > this.curseChance) return;
            
            this.offerCurseChoice();
        }
        
        offerCurseChoice() {
            this.lastCurseOffer = Date.now();
            
            // 选择一个随机诅咒
            const availableCurses = this.cursePool.filter(curse => 
                !this.activeCurses.find(active => active.id === curse.id)
            );
            
            if (availableCurses.length === 0) return;
            
            const selectedCurse = availableCurses[Math.floor(Math.random() * availableCurses.length)];\n            \n            this.showCurseChoice(selectedCurse);
        }
        
        showCurseChoice(curse) {
            // 暂停游戏
            if (window.gameEngine) {
                window.gameEngine.gameState = 'paused';
            }
            
            const choiceDiv = document.createElement('div');
            choiceDiv.id = 'curseChoice';
            choiceDiv.style.cssText = `
                position: fixed; top: 0; left: 0; width: 100%; height: 100%;
                background: rgba(0, 0, 0, 0.9); z-index: 25000;
                display: flex; align-items: center; justify-content: center;
                color: white; font-family: monospace;
            `;
            
            choiceDiv.innerHTML = `
                <div style="
                    text-align: center; max-width: 600px; padding: 40px;
                    background: linear-gradient(135deg, rgba(80, 0, 0, 0.95), rgba(40, 0, 40, 0.95));
                    border-radius: 15px; border: 3px solid #8B0000;
                ">
                    <h1 style="color: #FF4500; font-size: 36px; margin-bottom: 20px;">😈 黑暗契约</h1>
                    
                    <div style="margin: 30px 0; padding: 20px; background: rgba(0, 0, 0, 0.5); border-radius: 10px;">
                        <h2 style="color: #DC143C; margin-bottom: 10px;">${curse.name}</h2>
                        <p style="color: #FFB6C1; font-size: 16px; margin-bottom: 15px;">${curse.description}</p>
                        
                        <div style="color: #98FB98; padding: 15px; background: rgba(0, 100, 0, 0.2); border-radius: 8px;">
                            <strong>获得奖励:</strong><br>
                            <span style="color: #FFD700;">${curse.blessing.name}</span><br>
                            <span style="font-size: 14px;">${curse.blessing.description}</span>
                        </div>
                    </div>
                    
                    <div style="display: flex; gap: 20px; justify-content: center;">
                        <button id="acceptCurse" style="
                            background: linear-gradient(45deg, #8B0000, #DC143C);
                            border: none; color: white; padding: 15px 30px;
                            font-size: 18px; border-radius: 8px; cursor: pointer;
                            font-weight: bold;
                        ">接受诅咒</button>
                        
                        <button id="declineCurse" style="
                            background: linear-gradient(45deg, #555, #777);
                            border: none; color: white; padding: 15px 30px;
                            font-size: 18px; border-radius: 8px; cursor: pointer;
                        ">拒绝</button>
                    </div>
                    
                    <p style="font-size: 12px; color: #AAA; margin-top: 20px;">
                        接受诅咒将立即获得强大的奖励，但也会承受相应的负面效果。<br>
                        当前诅咒数量: ${this.activeCurses.length}/${this.maxCurses}
                    </p>
                </div>
            `;
            
            document.body.appendChild(choiceDiv);
            
            // 添加选择事件
            document.getElementById('acceptCurse').addEventListener('click', () => {
                this.acceptCurse(curse);
                this.removeChoiceDialog(choiceDiv);
            });
            
            document.getElementById('declineCurse').addEventListener('click', () => {
                this.declineCurse();
                this.removeChoiceDialog(choiceDiv);
            });
            
            // 添加按钮悬停效果
            this.addButtonEffects();
        }
        
        addButtonEffects() {
            const acceptBtn = document.getElementById('acceptCurse');
            const declineBtn = document.getElementById('declineCurse');
            
            acceptBtn?.addEventListener('mouseenter', () => {
                acceptBtn.style.background = 'linear-gradient(45deg, #DC143C, #FF6347)';
                acceptBtn.style.transform = 'translateY(-2px)';
                acceptBtn.style.boxShadow = '0 5px 15px rgba(220, 20, 60, 0.4)';
            });
            
            acceptBtn?.addEventListener('mouseleave', () => {
                acceptBtn.style.background = 'linear-gradient(45deg, #8B0000, #DC143C)';
                acceptBtn.style.transform = 'translateY(0)';
                acceptBtn.style.boxShadow = 'none';
            });
            
            declineBtn?.addEventListener('mouseenter', () => {
                declineBtn.style.background = 'linear-gradient(45deg, #777, #999)';
                declineBtn.style.transform = 'translateY(-2px)';
            });
            
            declineBtn?.addEventListener('mouseleave', () => {
                declineBtn.style.background = 'linear-gradient(45deg, #555, #777)';
                declineBtn.style.transform = 'translateY(0)';
            });
        }
        
        removeChoiceDialog(dialog) {
            dialog.style.animation = 'fadeOut 0.5s ease-out';
            setTimeout(() => {
                if (dialog.parentNode) {
                    document.body.removeChild(dialog);
                }
                
                // 恢复游戏
                if (window.gameEngine) {
                    window.gameEngine.gameState = 'playing';
                }
            }, 500);
        }
        
        acceptCurse(curse) {
            // 添加诅咒效果
            curse.effect();
            this.activeCurses.push(curse);
            
            // 给予奖励
            this.grantCurseBlessing(curse);
            
            // 显示确认信息
            window.gameEnhancements?.visualEffects?.createEventNotification(
                `😈 接受诅咒: ${curse.name}`,
                '#DC143C'
            );
            
            setTimeout(() => {
                window.gameEnhancements?.visualEffects?.createEventNotification(
                    `✨ 获得奖励: ${curse.blessing.name}`,
                    '#FFD700'
                );
            }, 1000);
            
            console.log(`😈 接受诅咒: ${curse.name}`);
            this.saveActiveCurses();
        }
        
        declineCurse() {
            window.gameEnhancements?.visualEffects?.createEventNotification(
                '🛡️ 拒绝了黑暗的诱惑',
                '#87CEEB'
            );
            
            console.log('🛡️ 拒绝诅咒');
        }
        
        grantCurseBlessing(curse) {
            const blessing = curse.blessing;
            
            switch (curse.id) {
                case 'fragile_bones':
                    if (window.player) {
                        window.player.maxHealth *= 2;
                        window.player.health = window.player.maxHealth;
                        if (window.player.updateHealthUI) window.player.updateHealthUI();
                        if (window.player.currentWeapon) {
                            window.player.currentWeapon.damage = Math.floor(window.player.currentWeapon.damage * 1.3);
                        }
                    }
                    break;
                case 'cursed_reload':
                    this.addBlessingEffect('instant_reload', true);
                    if (window.player?.currentWeapon) {
                        window.player.currentWeapon.fireRate *= 1.5;
                    }
                    break;
                case 'heavy_feet':
                    if (window.player) {
                        window.player.speed *= 3; // 抵消诅咒并额外增加80%
                    }
                    if (window.gameEnhancements?.dodgeSystem) {
                        window.gameEnhancements.dodgeSystem.dodgeCooldown *= 0.5;
                    }
                    break;
                case 'ammunition_curse':
                    this.addBlessingEffect('infinite_ammo', true);
                    if (window.player?.currentWeapon) {
                        window.player.currentWeapon.damage = Math.floor(window.player.currentWeapon.damage * 1.4);
                    }
                    break;
                case 'zombie_attraction':
                    this.addBlessingEffect('lifesteal', 5);
                    if (window.gameEnhancements?.comboSystem) {
                        this.addBlessingEffect('double_combo_rewards', true);
                    }
                    break;
            }
        }
        
        addCurseEffect(type, value) {
            if (!window.curseEffects) window.curseEffects = {};
            window.curseEffects[type] = value;
        }
        
        removeCurseEffect(type) {
            if (window.curseEffects) {
                delete window.curseEffects[type];
            }
        }
        
        addBlessingEffect(type, value) {
            if (!window.blessingEffects) window.blessingEffects = {};
            window.blessingEffects[type] = value;
        }
        
        update(deltaTime) {
            this.updateBlessingEffects();
        }
        
        updateBlessingEffects() {
            if (!window.blessingEffects || !window.player) return;
            
            // 狂战士模式
            if (window.blessingEffects.berserker_mode && window.player.currentWeapon) {
                const healthRatio = window.player.health / window.player.maxHealth;
                const damageMultiplier = 1 + (1 - healthRatio) * 2; // 最高3倍伤害
                
                if (!window.player.currentWeapon.originalDamage) {
                    window.player.currentWeapon.originalDamage = window.player.currentWeapon.damage;
                }
                
                window.player.currentWeapon.damage = Math.floor(
                    window.player.currentWeapon.originalDamage * damageMultiplier
                );
            }
        }
        
        // 检查伤害时的诅咒/祝福效果
        processPlayerDamage(damage) {
            let finalDamage = damage;
            
            // 诅咒效果：受伤增加
            if (window.curseEffects?.damage_taken_multiplier) {
                finalDamage *= window.curseEffects.damage_taken_multiplier;
            }
            
            // 祝福效果：死亡拯救
            if (window.blessingEffects?.death_save && window.player) {
                if (window.player.health - finalDamage <= 0) {
                    if (Math.random() < window.blessingEffects.death_save) {
                        window.player.health = 1;
                        window.gameEnhancements?.visualEffects?.createComboText(
                            window.player.x, window.player.y, '神圣拯救!', '#FFD700'
                        );
                        return 0; // 免疫这次伤害
                    }
                }
            }
            
            return finalDamage;
        }
        
        removeCurse(curseId) {
            const curseIndex = this.activeCurses.findIndex(curse => curse.id === curseId);
            if (curseIndex >= 0) {
                const curse = this.activeCurses[curseIndex];
                curse.remove();
                this.activeCurses.splice(curseIndex, 1);
                
                window.gameEnhancements?.visualEffects?.createEventNotification(
                    `😇 诅咒解除: ${curse.name}`,
                    '#87CEEB'
                );
                
                this.saveActiveCurses();
            }
        }
        
        saveActiveCurses() {
            const curseData = this.activeCurses.map(curse => ({ id: curse.id }));
            localStorage.setItem('activeCurses', JSON.stringify(curseData));
        }
        
        loadActiveCurses() {
            try {
                const saved = localStorage.getItem('activeCurses');
                if (saved) {
                    const curseData = JSON.parse(saved);
                    curseData.forEach(data => {
                        const curse = this.cursePool.find(c => c.id === data.id);
                        if (curse) {
                            curse.effect();
                            this.activeCurses.push(curse);
                            this.grantCurseBlessing(curse);
                        }
                    });
                }
            } catch (error) {
                console.error('诅咒数据加载失败:', error);
            }
        }
        
        getCurseInfo() {
            return {
                active: this.activeCurses.map(curse => ({
                    name: curse.name,
                    description: curse.description
                })),
                count: this.activeCurses.length,
                maxCount: this.maxCurses
            };
        }
    }
    
    // 全局初始化
    window.CurseSystem = CurseSystem;
    
    // 自动启动
    setTimeout(() => {
        if (!window.curseSystem && window.gameEngine) {
            window.curseSystem = new CurseSystem();
            window.curseSystem.initialize();
            window.curseSystem.loadActiveCurses();
            
            console.log('😈 诅咒系统已加载');
        }
    }, 6000);
    
})();